package com.mengtian_tech.smart_farm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mengtian_tech.smart_farm.model.BaseInfo;
import com.mengtian_tech.smart_farm.model.FieldInfo;
import com.mengtian_tech.smart_farm.model.PartitionInfo;
import com.mengtian_tech.smart_farm.service.SystemService;
import com.mengtian_tech.smart_farm.vo.AjaxJson;
import com.mengtian_tech.smart_farm.vo.PageResult;
import com.mengtian_tech.smart_farm.vo.Query;

/**
 * 基地信息控制器
 * @author wxd56
 */
@Controller
@RequestMapping("/zygl/szhgl/base")
public class BaseInfoController {

	@Autowired
	SystemService systemService;
	
	@RequestMapping("list")
	@ResponseBody
	public AjaxJson list(@RequestBody(required = false) BaseInfo baseInfo) {
		
		if(baseInfo == null) baseInfo = new BaseInfo();
		Query<BaseInfo> q = Query.create(baseInfo);
		PageResult<BaseInfo> result =  this.systemService.findPageList(q);		
		
		AjaxJson json = AjaxJson.getOk(result);
		return json;
	}
	
	/**
	 * 保存基地信息
	 * @return
	 */
	@RequestMapping("saveMarker")
	@ResponseBody
	public AjaxJson saveMarker(@RequestBody BaseInfo baseInfo) {
		this.systemService.save(baseInfo);
		AjaxJson json =  AjaxJson.getOk("保存成功");
		json.setObject(baseInfo);
		return json;
	}
	
	/**
	 * 删除基地信息
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public AjaxJson delete(@RequestBody BaseInfo baseInfo) {
		
		//检查是否有分区和地块信息
		boolean exist = this.systemService.exist(
					Query.create(PartitionInfo.class)
					.eq("baseInfo.id", baseInfo.getId()));
		if(exist) {
			return AjaxJson.getError("请先删除分区！");
		}
		
		exist = this.systemService.exist(
						Query.create(FieldInfo.class)
						.eq("baseInfo.id", baseInfo.getId()));
		if(exist) {
			return AjaxJson.getError("请先删除地块！");
		}		
		
		this.systemService.delete(baseInfo);		
		
		AjaxJson json =  AjaxJson.getOk("删除成功");
		json.setObject(baseInfo);
		return json;
	}
	
}
